<?php
declare (strict_types = 1);

namespace app\model;

use think\facade\Db;
use think\Model;

/**
 * @mixin \think\Model
 */
class Notice extends Model
{
    protected $autoWriteTimestamp = true;

    public static function deleteNotice($id) {
        $maxId = Notice::max('id');
        Notice::destroy($id);
        if($maxId == $id) {
            $max = Notice::max('id');
            $content = Notice::where('id',$max)->value('content');
            Db::name('setting')->where('page','home')->update(['notice' => $content]);
        }
    }
    /**
     * 获取公告分页
     */
    public static function pageList($page,$size) {
        $size = $size + 0;
        $start = ($page -1) * $size;
        $list = Db::name('notice')->order('id','desc')->limit($start,$size)->select()->toArray();
        $total = self::count();
        return compact('list','total');
    }
    /**
     * 顶置公告
     */
    public static function topNotice($id,$top) {
        $notice = Notice::find($id);
        $topId = 0;
        if($top == 1) {
           $notice->old_id = $id;
           $notice->top = 1;
           $topNotice = Notice::where('top', 1) -> find();
           if($topNotice) {
               $topId = $topNotice->id;
               $topNotice->top = 0;
               $topNotice->id = $topNotice->old_id;
               $topNotice->save();
           } else {
             $topId = Notice::max('id') + 1;
           }
           $notice->id = $topId;
            Db::name('setting')->where('page','home')->update(['notice' => $notice ->content]);
           $notice->save();
        } else {
           $notice->id = $notice->old_id;
           $notice->top = 0;
            $notice->save();
            $max = Notice::max('id');
            $content = Notice::where('id',$max)->value('content');
            Db::name('setting')->where('page','home')->update(['notice' => $content]);
        }

    }
    /**
     * 发布公告
     */
     public static function saveNotice($data) {
        $data['create_time'] = date('Y-m-d h:i:s', time());
        $id = Db::name('notice') ->insertGetId($data);
        $notice = Notice::where('top', 1) -> find();
        if($notice) {
            $notice->id = $id + 1;
            $notice->save();
        } else {
            Db::name('setting') -> where('page','home')->update(['notice' => $data['content']]);
        }
     }

}
